<template>
	<view class="full-page root-style">
		<u-navbar :title="studyStore.Title"></u-navbar>
		<view class="status-box">
			<view class="topbarview" v-if="showTopbar">
				<view class="count-item" style="border-right: 1px solid #E2E0E3;">
					<view class="count-tag">词句统计</view>
					<view style="font-size: var(--text-14); font-weight: bold;">{{RemeberCnt}}<text style="font-size: var(--text-12);color:#777;">词</text>/{{RemeberSentenceCnt}}<text style="font-size: 12px;color:#777;">句</text></view>
				</view>
				<view class="count-item" style="border-right: 1px solid #E2E0E3;">
					<view class="count-tag">词汇进度</view>
					<view style="font-size: var(--text-14); font-weight: bold;">
						<text style="color: #C06E7A;">{{RemeberLvxCnt}}</text>-<text style="color: #3CA692;">{{RemeberLv0Cnt}}</text>
					</view>
				</view>
				<view class="count-item" style="border-right: 1px solid #E2E0E3;">
					<view class="count-tag">
						<text>消消乐</text>
						<text v-if="ProcessCnt>0" @click="gouseexam" style="background-color: #777;color: #fff; margin-left: 10px; padding:0px 5px; border-radius: 3px;">消</text>
					</view>
					<view style="font-size: var(--text-14); font-weight: bold;">
						<text style="color: #C06E7A;">{{ProcessCnt}}</text>/<text style="color: #3CA692;">20</text>
					</view>
				</view>
				<view class="count-item expired-time"> 
					<view class="count-tag" style="color:#777">{{ExpiredTime}}</view>
					<view style="">
						<text @click="classover" style="background-color: #777; font-size: var(--text-12); color:#fff; padding:2px 10px; border-radius: 5px;">下 课</text>
					</view>
				</view>
			</view>
		</view>
		<view class="h-10rpx flex-shrink-0"></view>
		
		<StepPrevLesson v-if="visibleModule(1)" @module-event="moduleEvent" />
		<StepSentence v-if="visibleModule(2)" timer-bar-sty="top:0" @module-event="moduleEvent" />
		<StepWordLearn v-if="visibleModule(3)" @module-event="moduleEvent" />
		<StepGroupTest v-if="visibleModule(4)" err-learn @module-event="moduleEvent" />
		<StepLinkTest v-if="visibleModule(5)" @module-event="moduleEvent" />
		<StepFinalResult v-if="visibleModule(6)" :lesson-uuid="LessonUUID" />
		<TesterSetting @re-test="handleReTest" />
	
		<u-modal v-model="showCoinBox" @confirm="confirmCoinBox" :title-style="{color: 'red'}">
			<view class="h-20px"></view>
			<view class="flex items-center justify-center">
				恭喜你获得20颗<u-image src="https://nx5.abc5g.com/images/been2.png" mode="aspectFit" width="30px" height="26px" ></u-image>
			</view>
			<view class="h-20px"></view>
		</u-modal>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import StepPrevLesson from "./modules/step-prev-lesson";
	import StepSentence from "./modules/step-sentence";
	import StepWordLearn from "./modules/step-word-learn";
	import StepGroupTest from "./modules/step-group-test";
	import StepLinkTest from "./modules/step-link-test";
	import StepFinalResult from "./modules/step-final-result";
	import TesterSetting from "./modules/tester-setting.vue";
	import { OT, dateFormat, getUuid, isString, ktlapi, lodash } from "@/utils";
	import { getPrevLessonWord, getLessonSentence } from './utils/api';
	import { ISentence, IWord, useStudyStore } from '@/store/study';
	
	const studyStore = useStudyStore();
	const wokflow_step = [{
		"StepName":"1",
		"Target":"step-prev-lesson"
	},{
		"StepName":"2",
		"Target":"step-prev-lesson"
	},
	{
		"StepName":"3",
		"Target":"step-prev-lesson"
	},
	{
		"StepName":"4",
		"Target":"step-prev-lesson"
	},
	{
		"StepName":"5",
		"Target":"step-prev-lesson"
	}]
	const showCoinBox = ref(false);
	const LessonInfo = ref<any>({});
	const GetDataTime = ref<any>(0);
	const showTopbar = ref(true);
	// 本节课的熟词数量
	const RemeberLv0Cnt = ref(0);
	// 本节课的生词数量
	const RemeberLvxCnt = ref(0);
	// 本节课所学的句子数量
	const RemeberSentenceCnt = ref(0);
	// 本节课所学的词汇数量
	const RemeberCnt = ref(0);
	// 本轮生词进度
	const ProcessCnt = ref(0);
	let interruptTime = new Date().getTime();
	
	// 课程ID
	const LessonUUID = ref(null);
	// 已经使用的时间
	const ExpiredTime = ref('');
	// 组件条件渲染状态
	const visibleModule = computed(() => {
		return (stepNum: number) => studyStore.step === stepNum;
	});
	const TestSentenceId = ref('');
	
	// 获取上一节课需要复习的词汇
	const getPrevWord = async () => {
		const prevResp = await getPrevLessonWord(LessonUUID.value);
		var prevRespList = lodash.get(prevResp, 'data.tables[0].table', []);
		
		// prevRespList = [
		// 	{"WordId":1,"Word":"A-EN","Mean":"A-中文","MP3":"https://crdlive.abc5g.com/SDEAudios/e403b598-a62d-4fca-ab57-2d853b024d2c.mp3"},
		// 	{"WordId":2,"Word":"B-EN","Mean":"B-中文","MP3":"https://crdlive.abc5g.com/SDEAudios/9dc28a2b-c906-487b-906f-ccb2749eb9f0.mp3"},
		// 	{"WordId":3,"Word":"C-EN","Mean":"C-中文","MP3":"https://crdlive.abc5g.com/SDEAudios/ca3a87cd-2a48-4a00-9fa7-3e6de80b1411.mp3"},
		// 	{"WordId":4,"Word":"D-EN","Mean":"D-中文","MP3":"https://crdlive.abc5g.com/SDEAudios/62b5c821-b8ce-4942-b7ed-54f08c257ac4.mp3"},
		// 	{"WordId":5,"Word":"E-EN","Mean":"E-中文","MP3":"https://crdlive.abc5g.com/SDEAudios/4fb9257b-67c0-4ad7-9a78-22372d880f91.mp3"},
		// ]
		
		if(prevRespList.length > 0){
			// console.log(prevRespList);
			// 备用混淆词汇
			const shuffleWords = lodash.get(prevResp, 'data.tables[1].table', []);
			// 获取课程信息
			LessonInfo.value = lodash.get(prevResp, 'data.tables[2].table[0]', {});
			if(LessonInfo.value.NowTime){
				GetDataTime.value = new Date(dateFormat(LessonInfo.value.NowTime, 'yyyy/MM/dd HH:mm:ss')).getTime();
			}
			studyStore.setShuffleWords(shuffleWords);
			studyStore.setWordGroup(prevRespList);
			studyStore.setStep(1, '复习巩固');
			return;
		}
		
		// 获取本次需要学习的句子和词汇
		handleNextGroup();
	}
	
	// 获取要学习的句子与词汇
	const getNextSentenceAndWords = async () => {
		const lessonSentenceResp = await getLessonSentence(LessonUUID.value)
		
		// 学习句子
		const sentence: ISentence = lodash.get(lessonSentenceResp, 'data.tables[0].table[0]', {});
		// 学习词汇
		const wordGroup: IWord[] = lodash.get(lessonSentenceResp, 'data.tables[1].table', []);
		
		// 备用混淆词汇
		const shuffleWords = lodash.get(lessonSentenceResp, 'data.tables[2].table', []);
		// 是否是未完成词汇，如果是，直接进入学习阶段
		const IsLastClass: boolean = lodash.get(lessonSentenceResp, 'data.tables[3].table[0].IsLastClass', false);
		// 获取课程信息
		LessonInfo.value = lodash.get(lessonSentenceResp, 'data.tables[4].table[0]', {});
		if(LessonInfo.value.NowTime){
			GetDataTime.value = new Date(dateFormat(LessonInfo.value.NowTime, 'yyyy/MM/dd HH:mm:ss')).getTime();
		}
		interruptTime = new Date().getTime();
		if (isString(sentence.WordIds)) {
			sentence.WordIds = JSON.parse(sentence.WordIds as unknown as string);
		}
		
		wordGroup.forEach(item => {
			if (item.Methods) {
				item.Methods = JSON.parse(item.Methods);
			}
			
			item.NeedRemeber = IsLastClass ? true : false;
			item.SentenceSnapshot = {
				SentenceEn: sentence.SentenceEn,
				SentenceCn: sentence.SentenceCn,
				Audio: sentence.Audio,
				Media: sentence.Media,
				WordIds: sentence.WordIds
			}
		})
		
		studyStore.setSentence(sentence);
		studyStore.setWordGroup(wordGroup);
		studyStore.setShuffleWords(shuffleWords);
		studyStore.setIsLastClass(IsLastClass);
		
		return IsLastClass;
	}
	
	const handleAddRemeberProcess = (inFinished: boolean, callback: any) => {
		studyStore.wordGroup.forEach(item => {
			if (item.LostLv === undefined){
				item.LostLv = item.NeedRemeber ? 18 : 0
			}
		})
		ktlapi({
			apiurl: OT.CommandAddSet,
			action: 'Cus_AddRemeberProcess',
			data: studyStore.wordGroup.map(wordInfo => {
				return {
					WordId: wordInfo.WordId,
					LessonId: studyStore.LessonUUID,
					SentenceSnapshot: JSON.stringify(wordInfo.SentenceSnapshot),
					LostLv: wordInfo.LostLv,
					IsFinished: wordInfo.NeedRemeber ? (inFinished ? 1 : 0) : 1
				}
			})
		}).then((res: any) => {
			callback && callback(res);
		})
	}
	
	const confirmCoinBox = () => {
		
	}
	
	// 重置测试
	const handleReTest = (sentenceId: any) => {
		console.log('sentenceId', sentenceId)
		TestSentenceId.value = sentenceId;
		if(!sentenceId) return;
		ktlapi({
			apiurl: OT.CommandSet,
			action: 'Cus_GetStudySentenceBySentenceId',
			data: {
				SentenceId: sentenceId
			}
		}).then(resp => {
			// 学习句子
			const sentence: ISentence = lodash.get(resp, 'data.tables[0].table[0]', {});
			// 学习词汇
			const wordGroup: IWord[] = lodash.get(resp, 'data.tables[1].table', []);
			
			// 备用混淆词汇
			const shuffleWords = lodash.get(resp, 'data.tables[2].table', []);
			if (isString(sentence.WordIds)) {
				sentence.WordIds = JSON.parse(sentence.WordIds as unknown as string);
			}
			wordGroup.forEach(item => {
				if (item.Methods) {
					item.Methods = JSON.parse(item.Methods);
				}
				
				item.NeedRemeber = false;
				item.SentenceSnapshot = {
					SentenceEn: sentence.SentenceEn,
					SentenceCn: sentence.SentenceCn,
					Audio: sentence.Audio,
					Media: sentence.Media,
					WordIds: sentence.WordIds
				}
			})
			
			studyStore.setSentence(sentence);
			studyStore.setWordGroup(wordGroup);
			studyStore.setShuffleWords(shuffleWords);
			
			studyStore.setTitle('单词筛选');
			studyStore.setStep(99);
			nextTick(() => studyStore.setStep(2));
		})
	}
	
	// 组件事件调度
	const moduleEvent = ({ action, payload }) => {
		switch (action) {
			case 'next': handleNext(payload); break;
			case 'refreshcnt': getLessonProcess(); break;
		}
	}
	
	// handleNextGroup 测试工具模式
	const handleNextGroupTester = (IsLastClass: boolean) => {
		if (IsLastClass) {
			// 开启了单词学习步骤
			if (studyStore.tester.studyWord) {
				studyStore.setStep(3, '单词学习');
			} else {
				// 如果没开启学习步骤，直接进入测试步骤
				studyStore.setStep(4, '单词学习');
			}
		} else {
			studyStore.setTitle('单词筛选');
			if (studyStore.step === 2){
				studyStore.setStep(99);
				nextTick(() => studyStore.setStep(2));
			} else {
				studyStore.setStep(2);
			}
		}
	}
	
	const handleTestNextGroup = () => {
		ktlapi({
			apiurl: OT.CommandSet,
			action: 'Cus_GetTestStudyProcSentence',
			data: {
				LessonUUID: LessonUUID.value,
				SentenceId: TestSentenceId.value
			}
		}).then(resp => {
			// 学习句子
			const sentence: ISentence = lodash.get(resp, 'data.tables[0].table[0]', {});
			// 学习词汇
			const wordGroup: IWord[] = lodash.get(resp, 'data.tables[1].table', []);
			
			// 备用混淆词汇
			const shuffleWords = lodash.get(resp, 'data.tables[2].table', []);
			
			if (isString(sentence.WordIds)) {
				sentence.WordIds = JSON.parse(sentence.WordIds as unknown as string);
			}
			
			wordGroup.forEach(item => {
				if (item.Methods) {
					item.Methods = JSON.parse(item.Methods);
				}
				
				item.NeedRemeber = true;
				item.SentenceSnapshot = {
					SentenceEn: sentence.SentenceEn,
					SentenceCn: sentence.SentenceCn,
					Audio: sentence.Audio,
					Media: sentence.Media,
					WordIds: sentence.WordIds
				}
			})
			
			studyStore.setSentence(sentence);
			studyStore.setWordGroup(wordGroup);
			studyStore.setShuffleWords(shuffleWords);
			
			handleNextGroupTester(true);
		})
	}
	
	// 执行获取要学习的句子与词汇
	const handleNextGroup = () => {
		getLessonProcess();
		getNextSentenceAndWords().then((IsLastClass) => {
			// 如果开启了测试工具
			if (studyStore.tester.isTestMode) {
				handleNextGroupTester(IsLastClass);
			} else {
				// 正常逻辑
				if (IsLastClass) {
					studyStore.setStep(3, '单词学习');
				} else {
					studyStore.setTitle('单词筛选');
					if (studyStore.step === 2){
						studyStore.setStep(99);
						nextTick(() => studyStore.setStep(2));
					} else {
						studyStore.setStep(2);
					}
				}
			}
		})
	}
	
	const getLessonProcess = () => {
		ktlapi({
			apiurl: OT.CommandSet,
			action: 'GetLessonProcess',
			data: {
				LessonId: LessonUUID.value
			}
		}).then((data) => {
			lodash.get(data, 'data[0].RemeberCnt', 0);
			// 获取本节课的熟词数量
			RemeberLv0Cnt.value = lodash.get(data, 'data.tables[0].table[0].RemeberLv0Cnt', 0);
			// 获取本节课的生词数量
			RemeberLvxCnt.value = lodash.get(data, 'data.tables[1].table[0].RemeberLvxCnt', 0);
			// 获取本节课所学的句子数量
			RemeberSentenceCnt.value = lodash.get(data, 'data.tables[2].table[0].RemeberSentenceCnt', 0);
			// 获取本节课所学的词汇数量
			RemeberCnt.value = lodash.get(data, 'data.tables[3].table[0].RemeberCnt', 0);
			// 获取本轮生词进度
			ProcessCnt.value = lodash.get(data, 'data.tables[4].table[0].ProcessCnt', 0);
			// const remeberCnt = lodash.get(data, 'data[0].RemeberCnt', 0);
			// studyStore.setRemeberCnt(remeberCnt);
		})
	}
	
	/** 第四步完成执行的事件，实际上是第四步完成后，统计数据进入下一步骤/阶段的动作 */
	const overSetp4 = () => {
		ktlapi({
			action: 'Cus_GetLessonRemeberCnt',
			data: {
				LessonId: LessonUUID.value
			}
		}).then((res: any) => {
			ProcessCnt.value = res.data[0].Cnt;
			if (res.data[0].Cnt >= 20) { 
				studyStore.setStep(5, '学生自测');
			} else {
				handleNextGroup()
			}
		})
	}
	const handleNext = (_payload: any) => {
		//console.log('=== handleNext >>> payload', payload)
		switch(studyStore.step){
			// 复习上一课词汇 => 2
			case 1:
				handleNextGroup();
				break;
			// 学习: 筛选词汇 + 二次验证 => 3
			case 2:
				if (TestSentenceId.value) {
					handleTestNextGroup();
				} else {
					handleNextGroup();
				}
				break;
			// 学习: 生词学习
			case 3:
				// 发生在学习步骤（词汇详情）完成之后执行
				studyStore.setStep(4);
				break;
			// 学习: 生词测试
			case 4: 
				// 获取本轮生词进度, 发生在句子挖空的测试完成之后执行
				overSetp4();
				break;
			// 学习: 链接测试 + 最终反馈
			case 5:
				handleNextGroup();
				break;
		}
	}
	
	function gouseexam(){
		uni.showModal({
			title: '提示',
			content: '是否进入自测环节?',
			success: function (res) {
				if (res.confirm) {
					studyStore.setStep(5);
				} else if (res.cancel) {
					//console.log('用户点击取消');
				}
			}
		}); 
	}
	
	function classover(){
		uni.showModal({
			title: '提示',
			content: '是否结束课程?',
			success: function (res) {
				if (res.confirm) {
					ktlapi({
						action: 'Cus_OverLesson',
						data: {
							LessonUUID: LessonUUID.value
						}
					}).then(() => {
						showTopbar.value = false; 
						studyStore.setStep(6, '课程报告');
						showCoinBox.value = true;
					})
				} else if (res.cancel) {
					//console.log('用户点击取消');
				}
			}
		}); 
	}
	
	function handleClassOver(){
		showTopbar.value = false; 
		ktlapi({
			action: 'Cus_OverLesson',
			data: {
				LessonUUID: LessonUUID.value
			}
		}).then(() => { 
			studyStore.setStep(6, '课程报告');
			showCoinBox.value = true;
		})
	}
	
	// 初始化数据
	const initData = () => {
		
		// 如果开启了测试工具
		if (studyStore.tester.isTestMode) {
			if (studyStore.tester.prevClassBack) {
				// 获取上一节课的词汇
				if (studyStore.step < 2) {
					return getPrevWord();
				}
			}
			// 获取本次需要学习的句子和词汇
			handleNextGroup()
			return;
		}
		
		// 获取上一节课的词汇
		if (studyStore.step < 2) {
			return getPrevWord();
		}
		
		// 获取本次需要学习的句子和词汇
		handleNextGroup()
	}
	
	// 页面加载钩子函数
	onLoad(query => {
		LessonUUID.value = query.LessonId;
		studyStore.setLessonUUID(LessonUUID.value);
	})
	
	let overTipsTimer: any = null;
	// 页面加载完成钩子函数
	onMounted(() => {
		studyStore.init();
		initData();

		overTipsTimer = setInterval(() => {
			// 如果两个时间之和大于课程结束时间，进行提示
			const nowTimeNum = new Date().getTime();
			const { StudyDay, StartTime, EndTime } = LessonInfo.value;
			if(GetDataTime.value === 0 || !StudyDay || !EndTime) {
				return;
			}
			
			const formatStartTime = StartTime.split(':').filter((_item: any, index: number) => index < 3).join(":");
			const startTimeNum = new Date(dateFormat(StudyDay, 'yyyy/MM/dd') + ' ' + formatStartTime).getTime();
			
			const ExpiredSecond = (nowTimeNum - startTimeNum)/1000;
			const hour = Math.floor(ExpiredSecond/60/60);
			const minute = Math.floor((ExpiredSecond - hour*60*60)/60);
			const second = Math.floor(ExpiredSecond - hour*60*60 - minute*60);
			ExpiredTime.value = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
		}, 1000)
	})
	
	onUnmounted(() => {
		clearInterval(overTipsTimer);
	})
</script>

<style lang="scss" scoped>
	.count-item{
		text-align: center;
		flex: 1;
		margin-top: 10px;
		margin-bottom: 10px;
		
		.count-tag{
			font-size: var(--text-12);
			
			/* #ifdef H5 */
			margin-bottom: 3px;
			/* #endif */
			
			/* #ifdef MP */
			margin-bottom: 5px;
			/* #endif */
		}
	}
	.count-item.expired-time{
		/* #ifdef H5 */
		margin-top: 12px;
		/* #endif */
		
		/* #ifdef MP */
		margin-top: 10px;
		/* #endif */
		
		.count-tag{
			font-size: var(--text-12);
			
			/* #ifdef H5 */
			margin-top: -3px;
			/* #endif */
			margin-bottom: 0;
		}
	}
	
	.topbarview{
		display: flex;
		width:90%; 
		margin:0px auto;
		background-color: #F6F4F7;
	}
	
	.slot-wrap{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.full-page {
		display: flex;
		flex-flow: column;
		overflow: hidden;
	}
	
	.status-box{
		flex-shrink: 0;
	}
</style>